package com.gua.otap.daoImpl;

import java.util.List;

import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.gua.framework.daoImpl.BaseDaoImpl;
import com.gua.otap.constants.DBConstant;
import com.gua.otap.dao.IUserLoginDao;
import com.gua.otap.pojo.Otault;
import com.gua.otap.security.SecurityUser;
import com.gua.otap.security.UserRole;

public class UserLoginDaoImpl extends BaseDaoImpl implements IUserLoginDao,UserDetailsService{

	public UserDetails loadUserByUsername(final String ultlogin)
			throws UsernameNotFoundException, DataAccessException {
		Session session = null;
		try{
			session = getSessionFactory().openSession();
			List<Otault> users = session.createQuery(" from Otault ult where ult.ultname='" + ultlogin + "' and ult.isactive ='" + DBConstant.YES_VALUE + "'").list();

	        if (users == null || users.isEmpty()) {
	            throw new UsernameNotFoundException("user '" + ultlogin + "' not found...");
	        } else {
	        	Otault ult = users.get(0);
	        	SecurityUser user = new SecurityUser();
	        	user.setAccountNonExpired(DBConstant.YES_VALUE.equalsIgnoreCase(ult.getIsactive()));
	        	user.setAccountNonLocked(DBConstant.YES_VALUE.equalsIgnoreCase(ult.getIsactive()));
	        	user.setCredentialsNonExpired(DBConstant.YES_VALUE.equalsIgnoreCase(ult.getIsactive()));
	        	user.setEnabled(DBConstant.YES_VALUE.equalsIgnoreCase(ult.getIsactive()));
	        	user.setPassword(ult.getUltpassword());
	        	user.setUsername(ult.getUltname());
			    user.setAuthorities(getAuthorities());
	        	return (UserDetails) user;
	        }
		} catch (Exception e) {
			 e.printStackTrace();
			 throw new UsernameNotFoundException("user '" + ultlogin + "' not found...");
		}
		finally {
			if(session != null && session.isOpen()){
				session.close();		
			}
		}
	}
	
	public GrantedAuthority[] getAuthorities(){
		//UserRole userRole = new UserRole("user");
		GrantedAuthority[] auth = new GrantedAuthority[1];
		auth[0] = new UserRole();
		return auth;
	}

}
